import axios, { Method } from 'axios'
import { showToast } from '@/utils/toast'
import { toFormData } from '@/utils/form-data'
import { Authorization } from '@/utils/cookie'

const showError = (message: string) => {
  showToast('error', message)
  throw new Error(message)
}

const instance = axios.create({
  baseURL: '/api',
  timeout: 6000,
  xsrfCookieName: Authorization,
  xsrfHeaderName: Authorization,
})

instance.interceptors.request.use(config => config, showError) //请求出错

instance.interceptors.response.use(response => {
  if (response.status >= 200 && response.status <= 300) return response.data //正常返回数据
  if (response.status === 401) return //token过期
  showError(response.statusText) //其他错误
}, showError)

export const http = <T>(method: Method, url: string, data?: unknown, contentType?: ContentType) =>
  instance.request<T, ResponseData<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: contentType === 'multipart/form-data' ? toFormData(data) : data,
  })
